

package com.zzb.framework.modules.role.service.impl;

import java.util.*;

import com.zzb.framework.modules.role.dao.SysUserRoleDAO;
import com.zzb.framework.modules.role.service.SysUserRoleService;
import com.zzb.framework.utils.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zzb.framework.modules.role.dao.SysMenuDAO;
import com.zzb.framework.modules.role.dao.SysUserDAO;
import com.zzb.framework.modules.role.dao.SysUserTokenDAO;
import com.zzb.framework.modules.role.entity.SysMenuEntity;
import com.zzb.framework.modules.role.entity.SysUserEntity;
import com.zzb.framework.modules.role.entity.SysUserTokenEntity;
import com.zzb.framework.modules.role.service.ShiroService;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDAO sysMenuDAO;
    @Autowired
    private SysUserDAO sysUserDAO;
    @Autowired
    private SysUserRoleDAO sysUserRoleDAO;
    @Autowired
    private SysUserTokenDAO sysUserTokenDAO;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuDAO.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserDAO.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenDAO.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        SysUserEntity sysUserEntity = sysUserDAO.selectById(userId);
        List<Long> ids = sysUserRoleDAO.queryRoleIdList(userId);
        sysUserEntity.setRoleIdList(ids);
        return sysUserEntity;
    }
}
